<template>
    <div class="role-wrapper">
        <!-- 左侧角色列表 -->
         <cardBox class="left-wrapper" title="角色列表" icon="&#xe613;">
            <template #right>
                <el-button type="primary" icon="el-icon-circle-plus-outline" 
                    :underline="false" size="mini" 
                    @click="handleShowRoleMenuDialog({},false)" 
                    v-if="showRoleAdd">
                    新增角色
                </el-button>
            </template>
            <div class="role-list">
                <div v-for="item in roleList" :key="item.roleId" 
                    class="role-item" 
                    :class="{ 'active': currentRoleID == item.roleId }"
                    @click="handleSelectRole(item.roleId)">
                    <div class="role-info">
                        <i class="iconfont">&#xe624;</i> 
                        <span class="role-name">{{ item.roleName }}</span>
                    </div>
                    <div class="role-actions" @click.stop>
                        <el-tooltip effect="dark" content="修改角色" placement="top">
                            <el-button type="primary" icon="el-icon-edit" size="mini" 
                                @click="handleShowRoleMenuDialog(item,true)" 
                                v-if="showRoleEdit">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="删除角色" placement="top">
                            <el-button type="danger" icon="el-icon-delete" size="mini" 
                                @click="handleDelRole(item)" 
                                v-if="showRoleDel">
                            </el-button>
                        </el-tooltip>
                    </div>
                </div>
            </div>
        </cardBox>

        <!-- 右侧权限表格 -->
        <cardBox class="right-wrapper" title="权限配置" icon="&#xe62a;" v-loading="isloading" 
        element-loading-text="权限保存中，请稍后"  
         element-loading-spinner="el-icon-loading">
            <template #right>
                <div class="permission-actions">
                    <el-button type="primary" size="mini" 
                        @click="handleSaveRoleClick" 
                        icon="el-icon-circle-check" 
                        v-if="showRoleEdit">
                        保存设置
                    </el-button>
                </div>
            </template>
            
            <div class="permission-content">
                <el-table :data="roleModelList" stripe row-key="moduleId" 
                    @select="handleSelectionModle" 
                    @select-all="handleSelectionModleAll" 
                    default-expand-all 
                    ref="roleModelList"
                    height="calc(100vh - 270px)">
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column label="名称" prop="moduleName" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <el-tooltip class="item" effect="dark" content="勾选后拥有查看此页面的权限" placement="top-start">
                                <el-checkbox v-model="scope.row.thisRole" 
                                :true-label="1" :false-label="0" 
                                @change="handleChangeThisOrgMenu(scope.row)">
                            </el-checkbox>
                            </el-tooltip>
                            {{ scope.row.moduleName }}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="增加" prop="opeAdd" >
                        <template slot-scope="scope">
                            <el-tooltip class="item" effect="dark" content="勾选后拥有此页面的新增权限" placement="top-start">
                                <el-checkbox v-model="scope.row.opeAdd" 
                                :true-label="1" :false-label="0" 
                                @change="handleChangeThisOrg(scope.row)">
                            </el-checkbox>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="修改" prop="opeEdit" >
                        <template slot-scope="scope">
                            <el-tooltip class="item" effect="dark" content="勾选后拥有此页面的修改/编辑权限" placement="top-start">
                               <el-checkbox v-model="scope.row.opeEdit" 
                                :true-label="1" :false-label="0" 
                                @change="handleChangeThisOrg(scope.row)">
                            </el-checkbox>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="删除" prop="opeDel" >
                        <template slot-scope="scope">
                            <el-tooltip class="item" effect="dark" content="勾选后拥有此页面的删除权限" placement="top-start">
                               <el-checkbox v-model="scope.row.opeDel" 
                                :true-label="1" :false-label="0" 
                                @change="handleChangeThisOrg(scope.row)">
                            </el-checkbox>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="审核" prop="opeCheck">
                        <template slot-scope="scope">
                            <el-tooltip class="item" effect="dark" content="勾选后拥有此页面的审核权限" placement="top-start">
                              <el-checkbox v-model="scope.row.opeCheck" 
                                :true-label="1" :false-label="0" 
                                @change="handleChangeThisOrg(scope.row)">
                            </el-checkbox>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </cardBox>

        <!-- 角色管理对话框 -->
        <el-dialog title="角色管理" v-dialogDrag :visible.sync="roleMenuDialog" 
            width="400px" :before-close="handleCloseRoleDialog">
            <el-form ref="roleForm" :model="roleForm" label-width="80px" size="medium">
                <el-form-item label="名称">
                    <el-input v-model="roleForm.roleName" placeholder="请输入角色名称"></el-input>
                </el-form-item>
            </el-form> 
            <div class="dialog-footer">
                <el-button size="small" @click="handleCloseRoleDialog" 
                    icon="el-icon-circle-close" class="cancel-btn">取消</el-button>
                <el-button type="primary" size="small" @click="handleSaveRole" 
                    icon="el-icon-circle-check" class="confirm-btn">保存配置</el-button>
            </div> 
        </el-dialog>
    </div>
</template>
<script>
import BoxWithTitle from '@/components/base/BoxWithTitle.vue'
import cardBox from "@/components/base/cardBox.vue";
import {roleList,roleEdit,roleAdd,roleDel,moduleByRoleId,setRoleModule} from '@/api/https'
export default({
    components:{BoxWithTitle,cardBox},
    props:{
        showRoleAdd:{
            type:Number,
            default:0
        },
        showRoleEdit:{
            type:Number,
            default:0
        },
        showRoleDel:{
            type:Number,
            default:0
        }
    },  
    data() {
        return {
            roleList:[],
            currentRoleID:'',
            roleMenuDialog:false,
            roleForm:{},
            roleEdit:false,
            roleModelList:[],
            isloading:false
        }
    },
    mounted(){
        this.getRoleMenuList()
    },
    methods:{
        getRoleMenuList(){
            roleList().then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.roleList = res.data
                    this.currentRoleID = res.data[0].roleId
                    this.onGetModelList()
                }else{
                    this.roleList = []
                }
            })
        },
        handleSelectRole(val){
            this.currentRoleID = val
            this.onGetModelList()
        },
        handleCloseRoleDialog(){
            this.roleMenuDialog = false
            this.roleForm = {}
        },
        handleShowRoleMenuDialog(data,isEdit){
            this.roleEdit = isEdit
            this.roleForm = {...data}
            this.roleMenuDialog = true
        },
        handleSaveRole(){
            if(!this.roleForm.roleName || this.roleForm.roleName.trim() === '') {
                this.$message.error('请输入角色名称！')
                return false
            }
            if(this.roleEdit){
                roleEdit(this.roleForm).then(res=>{  
                    if(res.isSuccess){
                        this.handleCloseRoleDialog()
                        this.getRoleMenuList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }else{
                roleAdd(this.roleForm).then(res=>{  
                    if(res.isSuccess){
                        this.handleCloseRoleDialog()
                        this.getRoleMenuList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }
        },
        handleDelRole(data){
            this.$confirm(`确认删除名称为 ${data.roleName} 的角色？`,'提示',{
                type:'warning'
            }).then(() => {
                roleDel({RoleId:data.roleId}).then(res=>{  
                    if(res.isSuccess){
                        this.getRoleMenuList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {});
        },
        onGetModelList(){
            moduleByRoleId({
                RoleID:this.currentRoleID
            }).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.roleModelList = res.data
                }else{
                    this.roleModelList = []
                }
            })
        },
        handleSelectionModle(selection,row){
            //角色管理 单选按钮（确认是否把增删改审核都全中）
            if(row.opeAdd == 1 && row.opeEdit == 1 && row.opeDel == 1 && row.opeCheck == 1 && row.thisRole == 1){
                this.$nextTick(()=>{
                    row.opeAdd = 0
                    row.opeEdit = 0
                    row.opeDel = 0
                    row.opeCheck = 0
                    row.thisRole = 0
                    this.$refs.roleModelList.toggleRowSelection(row, false)
                })
            }else{
                this.$nextTick(()=>{
                    row.opeAdd = 1
                    row.opeEdit = 1
                    row.opeDel = 1
                    row.opeCheck = 1
                    row.thisRole = 1
                    this.$refs.roleModelList.toggleRowSelection(row, true)
                })
            }  
            },
            toggleAllSelection(data,checked){
                data.forEach(item=>{
                    this.$refs.roleModelList.toggleRowSelection(item, checked)
                    if(checked){
                        item.opeAdd = 1
                        item.opeEdit = 1
                        item.opeDel = 1
                        item.opeCheck = 1
                        item.thisRole = 1
                    }else{
                        item.opeAdd = 0
                        item.opeEdit = 0
                        item.opeDel = 0
                        item.opeCheck = 0
                        item.thisRole = 0
                    }
                    if(item.children && item.children.length > 0){
                        this.toggleAllSelection(item.children,checked)
                    }
                })
            },
            handleSelectionModleAll(rows){
                this.roleModelList.forEach(node => {
                    if (rows.some(row => row === node)) {
                            // 设置该节点选中
                        this.$nextTick(()=>{
                            this.toggleAllSelection(this.roleModelList,true)
                        })
                    } else {
                            // 取消该节点选中
                        this.$nextTick(()=>{
                            this.toggleAllSelection(this.roleModelList,false)
                        })
                    }
                })
            },
            handleChangeThisOrgMenu(rows){
                if(rows.children && rows.children.length > 0){
                    rows.children.forEach(item=>{
                        item.thisRole = rows.thisRole
                    })
                }
            },
            handleSaveRoleClick(){
                this.isloading = true
                const list = this.toggleSelectOrg(this.roleModelList,[])
                setRoleModule(list).then(res=>{
                    if(res.isSuccess){
                        this.$message.success('保存成功！')
                        this.onGetModelList()
                        this.isloading = false
                    }else{
                         this.isloading = false
                        this.$message.error(res.errorMessage)
                    }
                })
            },
            toggleSelectOrg(data,list){
                data.forEach(item=>{
                    if(item.thisRole == 1){
                        list.push({
                            id:item.id,
                            roleId:this.currentRoleID,
                            opeAdd:item.opeAdd,
                            opeEdit:item.opeEdit,
                            opeSearch:item.opeSearch,
                            opeDel:item.opeDel,
                            opeCheck:item.opeCheck,
                            moduleId:item.moduleId
                        })
                    }
                    if(item.children && item.children.length > 0){
                        this.toggleSelectOrg(item.children,list)
                    }
                })
                return list
            },
            handleChangeThisOrg(rows){
                if(rows.opeAdd == 1 && rows.opeEdit == 1 && rows.opeDel == 1 && rows.opeCheck == 1 && rows.thisRole == 1 ){ 
                    this.$nextTick(()=>{
                    this.$refs.roleModelList.toggleRowSelection(rows, true)
                    })
                }else{
                    this.roleModelList.forEach(node => {
                    if (rows === node) {
                        // 设置该节点选中
                        this.$nextTick(()=>{
                        this.$refs.roleModelList.toggleRowSelection(rows, true)
                        })
                    } else {
                        // 取消该节点选中
                        this.$nextTick(()=>{
                        this.$refs.roleModelList.toggleRowSelection(rows, false)
                        })
                    }
                    })
                }
            },
    }
})
</script>
<style scoped lang="scss">
.role-wrapper {
    display: grid;
    grid-template-columns: 340px 1fr;
    height: calc(100vh - 180px);
    margin-top: 10px;
    
    .left-wrapper {
        width: 340px;
    }
    
    .right-wrapper {
        margin-left:10px;
    }
    
    .role-list {
        flex: 1;
        padding: 12px;
        overflow-y: auto;
        
        .role-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px 16px;
            margin-bottom: 8px;
            border-radius: 6px;
            border: 1px solid #e4e7ed;
            transition: all 0.3s ease;
            cursor: pointer;
            
            &:hover {
                background-color: #f5f7fa;
                border-color: #c0c4cc;
            }
            
            &.active {
                background-color: #ecf5ff;
                border-color: #409eff;
                .role-name {
                    font-weight: 600;
                    color: #409eff;
                }
                .role-info{
                    i{
                        color: #409eff;
                    }
                }
                
            }
            
            .role-info {
                display: flex;
                align-items: center;
                flex: 1;
                
                .iconfont {
                    margin-right: 8px;
                    color: #909399;
                }
                
                .role-name {
                    font-size: 14px;
                }
            }
            
            .role-actions {
                display: flex;
                gap: 4px;
                
                ::v-deep .el-button--mini {
                    padding: 5px;
                    width: 28px;
                    height: 28px;
                }
            }
        }
    }
    
    .permission-actions {
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        .current-role {
            font-size: 14px;
            color: #606266;
            font-weight: 500;
        }
    }
    
    .permission-content {
        flex: 1;
        margin-top: 12px;
    }
}
</style>